"use client"

import { useState } from "react";
import { CardBody, CardHeader, Input, Button, InputOtp, Form } from "@nextui-org/react";
import toast from "react-hot-toast";

import { login } from "@/api/user/login";
import { getCode, register } from "@/api/user/register";
import { UserInfo, FormInfo } from "@/type/login";
import { redirect } from "next/navigation";
import { setUserData } from "@/lib/features/login/loginSlice";
import { useAppDispatch } from "@/lib/hooks";


export default function Login() {

    const dispatch = useAppDispatch();



    const [isLoginState, setIsLoginState] = useState(false); // isLoginState

    const [isLodingState, setIsLodingState] = useState(false); // isLodingState

    const [isSendCodeState, setIsSendCodeState] = useState(false); // isSendCodeState

    const [userInfo, setUserInfo] = useState<UserInfo>({} as UserInfo);

    const [otp, setOtp] = useState<string>('');

    const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        const data: FormInfo = Object.fromEntries(new FormData(e.currentTarget)) as FormInfo;
        e.preventDefault();
        setIsLodingState(true)
        if (!isLoginState) {
            // 登录提交
            const result = await login(data.email, data.password)
            if (result.code === 200) {
                toast.success(result.message)                
                dispatch(setUserData(result.data))
                setIsLodingState(false)
                redirect("/")
            } else {
                toast.error(result.message)
            }
            setIsLodingState(false)
        } else {
            // 获取验证码
            const result = await getCode(data.email)
            if (result.code === 200) {
                setUserInfo({
                    email: data.email,
                    password: data.password,
                    otp: '',
                    validity: result.data.validity,
                    verify_code: result.data.verify_code
                })
                toast.success(result.message)
                setIsSendCodeState(!result.data.registered)
            } else {
                toast.error(result.message)
            }
            setIsLodingState(false)
        }
    }

    const onOtpSubmit = async (e: string) => {
        if (!isSendCodeState) {
            return toast.error("请先获取验证码")
        } else {
            const { message, code } = await register({ ...userInfo, otp: e })
            if (code === 200) {
                setIsLoginState(false)
                setIsSendCodeState(false)
                toast.success(message)
                setOtp("")
            } else {
                setIsSendCodeState(false)
                toast.error(message)
            }
        }
    }


    return (
        <>
            <CardHeader className="justify-center items-center">
                <span className={"text-2xl font-semibold text-slate-400"}>Attendance</span>
            </CardHeader>
            <CardBody className="scrollbar-hide">
                <Form validationBehavior="native" onSubmit={onSubmit} method="post" className="w-full" style={{ alignItems: 'unset' }}>
                    <div>
                        <Input isDisabled={isLodingState} isRequired label="Email" name="email" variant="underlined" size="sm" type="email"
                            validate={(value: string) => {
                                if (!value) return '需要电子邮件';
                                if (!/\S+@\S+\.\S+/.test(value)) return '电子邮件无效';
                                // 空格判断
                                if (/\s/.test(value)) return '电子邮件不能包含空格';
                            }}
                        />
                    </div>
                    <div>
                        <Input isDisabled={isLodingState} isRequired className="mt-2" name="password" label="Password" variant="underlined" size="sm" type="password"
                            validate={(value: string) => {
                                if (!value) return '需要密码';
                                if (value.length < 3) return '密码太短';
                                // 空格判断
                                if (/\s/.test(value)) return '密码不能包含空格';
                            }}
                        />
                    </div>
                    <div>
                        <InputOtp onValueChange={(v) => {
                            setOtp(v)
                        }} value={otp} isDisabled={!isSendCodeState && (!isLoginState || isLodingState)} onChange={(e) => {
                            if ((e.target as HTMLInputElement).value.length === 6) {
                                (e.target as HTMLInputElement).blur()
                            }
                        }} onComplete={(e) => onOtpSubmit(e)} color="default" name="code" className="mt-2 disabledWidthByInputOTP" label="Code" size="sm" length={6} variant="underlined" />
                    </div>
                    <div className="flex justify-between items-center mt-2">
                        <Button isDisabled={isSendCodeState} isLoading={isLodingState} className="mt-2 mr-1 w-2/3" type="submit" variant="ghost" color="success" size="sm">{!isLoginState ? 'Login' : 'GetCode'}</Button>
                        <Button isDisabled={isLodingState} onPress={() => setIsLoginState(!isLoginState)} className="mt-2 ml-1 w-1/3" variant="ghost" color="warning" size="sm">Toggle</Button>
                    </div>
                </Form>
            </CardBody>
        </>
    );
}

